//
//  EditableGroupImagesView.m
//  jsy
//
//  Created by  任辰东 on 2020/4/15.
//  Copyright © 2020 JSY. All rights reserved.
//

#import "EditableGroupImagesView.h"
#import "GroupImagesEditorCCell.h"
#import "LxGridViewFlowLayout.h"
#import "SDPhotoBrowser.h"

@interface EditableGroupImagesView ()<UICollectionViewDataSource,UICollectionViewDelegate, SDPhotoBrowserDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) LxGridViewFlowLayout *layout;
@property (nonatomic, assign) CGFloat column;
@property (nonatomic, assign) CGFloat margin;
@property (nonatomic, assign) CGFloat itemWH;
@property (nonatomic, strong) NSMutableArray *imagesArray;
@end

@implementation EditableGroupImagesView

-(instancetype)initWithColumn:(CGFloat)column
{
    self = [super init];
    if (self) {
        self.backgroundColor = UIColorFromHex(kColorWhite);
        _column = column;
        [self setupViews];
    }
    return self;
}

- (void)setImageUrls:(NSArray *)imageUrls
{
    self.imagesArray = [NSMutableArray arrayWithArray:imageUrls];
    [self.collectionView reloadData];
    self.collectionView.contentSize = CGSizeMake(0, (self.imagesArray.count/ self.column ) * (self.margin + self.itemWH));
}

- (void)setupViews
{
    [self configCollectionView];
}

- (void)configCollectionView {
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[LxGridViewFlowLayout alloc] init];
    
//    _column = 4;
    self.margin = 15;
    self.itemWH = (kScreenWidth - 15*2 - (_column - 1)  * self.margin) / _column;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = 0;
    _layout.minimumLineSpacing = self.margin;
    
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    CGFloat rgb = 244 / 255.0;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.scrollEnabled = NO;
    _collectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self addSubview:_collectionView];
    [_collectionView registerClass:[GroupImagesEditorCCell class] forCellWithReuseIdentifier:@"GroupImagesEditorCCell"];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view);
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.top.equalTo(self).offset(0);
        make.bottom.equalTo(self).offset(-0);
    }];
    
    [RACObserve(self.collectionView, contentSize) subscribeNext:^(NSValue *_Nullable x) {
        if (x.CGSizeValue.height > 0) {
            [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(x.CGSizeValue.height + self->_margin * 2);
            }];
        }
    }];
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    if (self.imagesArray.count == self.maxCount) {
        
        return self.imagesArray.count;
    }else{
        
        return self.imagesArray.count + 1;
    }
    
    return self.imagesArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GroupImagesEditorCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GroupImagesEditorCCell" forIndexPath:indexPath];
    
    if (indexPath.row == self.imagesArray.count ) {
        cell.imageView.image = [UIImage imageNamed:self.addBtnImgPath];
        cell.deleteBtn.hidden = YES;
        if (self.imagesArray.count == self.maxCount) {
            cell.imageView.image = nil;
        }
    } else {
        id obj = self.imagesArray[indexPath.row];
        if ([obj isKindOfClass:[NSString class]]) {
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:obj]];
        }else{
            cell.imageView.image = self.imagesArray[indexPath.row];
        }
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == self.imagesArray.count) {
        if (self.addImagesAction) {
            self.addImagesAction();
        }
    }else{
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        browser.currentImageIndex = indexPath.row;
        browser.sourceImagesContainerView = self.collectionView;
        browser.imageCount = self.imagesArray.count;
        browser.delegate = self;
        [browser show];
    }
}

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    NSURL *url = [NSURL new];
    if (index < self.imagesArray.count) {
        url = self.imagesArray[index];
    }
    return url;
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    GroupImagesEditorCCell *cell = (GroupImagesEditorCCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    UIImageView *imageView = cell.imageView;
    return imageView.image;
}

#pragma mark - Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    
    if (self.deleteImagesAction) {
        self.deleteImagesAction();
    }
    
    if ([self collectionView:self.collectionView numberOfItemsInSection:0] <= self.imagesArray.count) {
        [self.imagesArray removeObjectAtIndex:sender.tag];
        [self.collectionView reloadData];
        return;
    }
    
    [self.imagesArray removeObjectAtIndex:sender.tag];
    
    WeakSelf
    [_collectionView performBatchUpdates:^{
        StrongSelf
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        StrongSelf
        [self.collectionView reloadData];
    }];
    
    if (self.didFinishImages) {
        self.didFinishImages(self.imagesArray);
    }

}

#pragma mark - LxGridViewDataSource

/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < self.imagesArray.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < self.imagesArray.count && destinationIndexPath.item < self.imagesArray.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = self.imagesArray[sourceIndexPath.item];
    [self.imagesArray removeObjectAtIndex:sourceIndexPath.item];
    [self.imagesArray insertObject:image atIndex:destinationIndexPath.item];
    
    [_collectionView reloadData];
}

@end
